from sqlalchemy.orm import Session
from typing import List, Optional
from app.models.comment import Comment
from app.models.user import User
from app.schemas.comment import CommentCreate, CommentUpdate

class CommentCRUD:
    def create_comment(self, db: Session, *, comment: CommentCreate, author_id: int, entity_type: str, entity_id: int) -> Comment:
        """创建评论"""
        db_comment = Comment(
            content=comment.content,
            entity_type=entity_type,
            entity_id=entity_id,
            author_id=author_id,
            parent_id=comment.parent_id
        )
        db.add(db_comment)
        db.commit()
        db.refresh(db_comment)
        return db_comment

    def get_comment(self, db: Session, comment_id: int) -> Optional[Comment]:
        """获取单个评论"""
        return db.query(Comment).filter(Comment.id == comment_id).first()

    def get_comments_by_entity(self, db: Session, entity_type: str, entity_id: int) -> List[Comment]:
        """获取实体的所有评论"""
        return db.query(Comment).filter(
            Comment.entity_type == entity_type,
            Comment.entity_id == entity_id
        ).order_by(Comment.created_at.asc()).all()

    def get_comments_with_authors(self, db: Session, entity_type: str, entity_id: int):
        """获取实体的评论并包含作者信息"""
        return db.query(Comment, User).join(
            User, Comment.author_id == User.id
        ).filter(
            Comment.entity_type == entity_type,
            Comment.entity_id == entity_id
        ).order_by(Comment.created_at.asc()).all()

    def update_comment(self, db: Session, *, comment_id: int, comment_update: CommentUpdate) -> Optional[Comment]:
        """更新评论"""
        db_comment = db.query(Comment).filter(Comment.id == comment_id).first()
        if db_comment:
            if comment_update.content is not None:
                db_comment.content = comment_update.content
            db.commit()
            db.refresh(db_comment)
        return db_comment

    def delete_comment(self, db: Session, comment_id: int) -> Optional[Comment]:
        """删除评论"""
        db_comment = db.query(Comment).filter(Comment.id == comment_id).first()
        if db_comment:
            db.delete(db_comment)
            db.commit()
        return db_comment

comment = CommentCRUD()